package com.rongzhong.routing.check;

import java.io.File;
import java.util.Date;
import java.util.Map;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rongzhong.routing.checkNode.BaseNode;
import com.rongzhong.routing.hibernate.HibernateUtil;
import com.rongzhong.routing.main.RoutingInspecte;
import com.rongzhong.routing.util.Configuration;
import com.rongzhong.routing.util.PerformanceUtil;

/**
 * 
 * @author longxuegang@gmail.com
 * @version 1.0 2011-9-22
 * @since 1.0
 * @see
 */

public class BaseCheck {
	private Configuration configure = Configuration.getInstance();
	private HibernateUtil hibernate = HibernateUtil.getInstance();
	private PerformanceUtil perfUtil = PerformanceUtil.getInstance();
	private final String sourcefile = configure.getExcel();
	private final int dbCheckNumber = perfUtil.getDbCheckNumber(); //3
	private static final Logger log = LoggerFactory.getLogger(BaseCheck.class);
	
	public Map<Integer, Map<String,String>> getVariablesMap(){
		return RoutingInspecte.getInstance().getVariablesMap();
	}
	
	public void checkOutBase(){
		for (int dbIndex = 0; dbIndex < dbCheckNumber; dbIndex++) {
			BaseNode bean = initBaseNode(dbIndex); 
			Session session = null;
			Transaction tr =  null;
			try {
				session = hibernate.getStorageDBSession();
				tr = session.beginTransaction();
				session.saveOrUpdate(bean);
				operateExcel(bean);
				tr.commit();
			} catch (Exception e) {
				tr.rollback();
				log.error("checkOutBase run into error.",e);
			}finally{
				hibernate.closeSession(session);
			}
		}
	}
	
	public Object selectID(BaseNode bean){
		Session session = null;
		try {
			session = hibernate.getStorageDBSession();
			SQLQuery query = session.createSQLQuery("select ID from BASECHECK where DATE= ? and HOST= ?");
			query.setDate(0, bean.getDate());
			query.setString(1, bean.getHost());
			return query.uniqueResult();
		} catch (Exception e) {
			log.error("exist Aborts run into error.",e);
			return null;
		}finally{
			hibernate.closeSession(session);
		}
	}
	
	private BaseNode initBaseNode(int dbIndex) {
		BaseNode bean = new BaseNode();
		Map<String,String> variablesMap = getVariablesMap().get(dbIndex);
		bean.setHealthy(true);
		bean.setDate(new Date(System.currentTimeMillis()));
		bean.setHost(perfUtil.getDBHostPort(dbIndex));
		bean.setPort(new Integer(variablesMap.get("port")));
		bean.setBasedir(variablesMap.get("basedir"));
		bean.setDatadir(variablesMap.get("datadir"));
		bean.setPidFile(variablesMap.get("pid_file"));
		bean.setSocket(variablesMap.get("socket"));
		bean.setDataBackup(perfUtil.isMaster(dbIndex));
		bean.setServerVersion(variablesMap.get("version").replace("log", "") + variablesMap.get("version_comment"));
		Object ID = selectID(bean);
		bean.setId(ID == null ? 0 : new Integer(ID.toString()));
		return bean;
	}
	
	private void operateExcel(BaseNode bean) throws Exception{
		Workbook workBook = null;
		WritableWorkbook writeWorkBook = null;
		try {
			workBook = Workbook.getWorkbook(new File(sourcefile));
			writeWorkBook = Workbook.createWorkbook(new File(sourcefile), workBook);
			WritableSheet wsheet = writeWorkBook.getSheet(bean.getHost());
			int startColumnId = perfUtil.getStartPositionColumnId(wsheet,perfUtil.getLastReviewDate());
			int startRowId = perfUtil.getStartPositionRowId(wsheet,bean.getTaskNumber());
			Label label_0 = new Label(startColumnId, startRowId, "正常");
			Label label_1 = new Label(startColumnId, startRowId + 1, bean.getServerVersion());
			Label label_2 = new Label(startColumnId, startRowId + 2, bean.getPort() + "");
			Label label_3 = new Label(startColumnId, startRowId + 3, bean.getBasedir());
			Label label_4 = new Label(startColumnId, startRowId + 4, bean.getDatadir());
			Label label_5 = new Label(startColumnId, startRowId + 5, bean.getPidFile());
			Label label_6 = new Label(startColumnId, startRowId + 6, bean.getSocket());
			Label label_7 = new Label(startColumnId, startRowId + 7, bean.isDataBackup() ? "正常" : "无备份");
			wsheet.addCell(label_0);wsheet.addCell(label_1);wsheet.addCell(label_2);wsheet.addCell(label_3);
			wsheet.addCell(label_4);wsheet.addCell(label_5);wsheet.addCell(label_6);wsheet.addCell(label_7);
			writeWorkBook.write();
		} catch (Exception e) {
			log.error("operate excel run into error", e);
			throw new Exception(e);
		}finally{
			try {
				writeWorkBook.close();workBook.close();
			} catch (Exception e) {
				log.error("close WorkBook run into error",e);
				throw new Exception(e);
			}
		}
	}
}
